package com.fresh.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fresh.client.AuthFeignClient;
import com.fresh.common.ResponseResult;
import com.fresh.entity.User;
import com.fresh.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    AuthFeignClient authFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入authFilter");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        if(request.getURI().getPath().contains("/login")){
            System.out.println("/login请求直接放行");
            return chain.filter((exchange));
        }
        //判断权限
        User user = new User();
        user.setUserName(JwtUtil.getUname(request.getHeaders().getFirst("token")));
        user.setUrl(request.getURI().getPath());
        user.setMethod(request.getMethod().name());
        System.out.println("进入鉴权模块");
        ResponseResult<Boolean> flag = authFeignClient.author(user);
        if (!flag.getData()){
            byte[] bytes = null;
            try {
                bytes = new ObjectMapper().writeValueAsBytes(new ResponseResult<>(403,"no","没有权限,拦截"));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            response.getHeaders().add("content-type","application/json;charset=utf-8");
            DataBuffer data = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(data));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
